package com.zeng.stpro.modules.app.filter;

import com.zeng.stpro.modules.commons.utils.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author ZENGZHIJUN
 * @Date 2021/2/7 12:43
 */
//@WebFilter(urlPatterns = "/**", filterName = "ipFilter")
public class IpFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(getClass());

//    @Autowired
//    private HandlerExceptionResolver handlerExceptionResolver;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        doIpAllowedChecked(servletRequest,servletResponse);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private void doIpAllowedChecked(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String ipAddress = IpUtils.getRealIP(request);
        // 获取所有白名单IP list
        List<String> allowedList = new ArrayList<>();
        allowedList.add("10.180.15.201");
        if (!CollectionUtils.isEmpty(allowedList)) {
            if (!allowedList.contains(ipAddress)) {
                logger.error("{} 没有权限访问！",ipAddress);
                request.getRequestDispatcher("/error/ipNotAllowedException").forward(request, response);
                //handlerExceptionResolver.resolveException(request, response, null, new IpNotAllowedException(HttpStatus.FORBIDDEN.value(), "IP无权访问"));
                //return;
            }
        }
    }
}
